﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Data.Metadata.Edm;
using System.Data.Objects.DataClasses;
using SIMCObjetoNegocio;
using System.Collections;

namespace SIMCRepositorio
{
    public abstract class Database : ObjectContext, IDatabase
    {
        protected SIMCDB_Entities Context
        {
            get
            {
                return ObjectContextManager.Context;
            }
        }

        public Database() :
            base(System.Configuration.ConfigurationManager.ConnectionStrings["SIMCDB_Entities"].ConnectionString)
        {

        }       

        public void Insertar<TEntity>(TEntity entity) where TEntity : EntityObject
        {
            Context.AddObject(entity.GetEntitySetName(Context), entity);
            Context.SaveChanges();
        }

        public void Modificar<TEntity>(TEntity entity) where TEntity : EntityObject
        {
            object objetoOriginal;

            entity.EntityKey = Context.CreateEntityKey(entity.GetEntitySetName(Context), entity);

            if (Context.TryGetObjectByKey(entity.EntityKey, out objetoOriginal))
            {
                Context.ApplyPropertyChanges(entity.EntityKey.EntitySetName, entity);

                Context.SaveChanges();
            }
        }


        public void Eliminar<TEntity>(TEntity entity) where TEntity : EntityObject
        {
            object objetoOriginal;

            entity.EntityKey = Context.CreateEntityKey(entity.GetEntitySetName(Context), entity);

            if (Context.TryGetObjectByKey(entity.EntityKey, out objetoOriginal))
            {
                Context.DeleteObject(objetoOriginal);

                Context.SaveChanges();
            }
        }

        protected static PagedResult<T> BuildPagedResult<T>(IEnumerable entities, int total)
        {
            return new PagedResult<T>(entities.Cast<T>(), total);
        }
    }
}
